package com.sinodata.bsm.cicp.collector.common;

import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.constants.SeparatorConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangpeng
 * @version 3.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-15 下午3:46:15          wangpeng        3.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class FailedLoginCollector extends Collector {
    private static final Logger logger = Logger.getLogger(FailedLoginCollector.class);
    private final String shell = ". ./.profile;who /etc/security/failedlogin |tail -30";
    //private final String linuxShell = ". ./.bash_profile;lastb |head -30|awk '{print $1 \"\t\" $2 \"\t\" $5 \" \" $6 \" \" $7 \"\t\" $3}'|sed '1!G;h;$!d'";
    //匹配(用户名)(登录方式)(登录时间)(登录地址)
    private final String regex = "(\\S+)\\s+(\\S+)\\s+(\\w{3}\\s+\\d+\\s+\\d{2}:\\d{2})\\s+\\(?(\\d+\\.\\d+\\.\\d+.\\d+).*";
    private final Pattern pattern = Pattern.compile(regex);

    @Override
    public String[] getPropMeta() {
        return new String[] { "failedLoginUnm", "usersList" };
    }

    @Override
    public String[] getParamMeta() {
        return null;
    }

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        String[] propMetas = getPropMeta();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];
        BufferedReader reader = null;
        String strLine = null;
        String timeStamp;
        boolean flag = false;
        try {
            timeStamp = (String) this.getPersistentData(ip + "failedlogin");
            String newTimeStamp = timeStamp;
            if (timeStamp != null && timeStamp.matches("\\w{3}\\s+\\d+\\s+\\d{2}:\\d{2}")) {
                reader = CommandReader.getReader(ip, shell, 0, 0);
                StringBuilder sb = new StringBuilder();
                int failedLoginUnm = 0;
                while ((strLine = reader.readLine()) != null) {
                    Matcher matcher = pattern.matcher(strLine);
                    if (matcher.find()) {
                        if (flag && !matcher.group(3).trim().equals(timeStamp.trim())) {
                            failedLoginUnm++;
                            newTimeStamp = matcher.group(3);
                            sb.append(matcher.group(1)).append(SeparatorConstants.COL_SEPARATOR);
                            sb.append(matcher.group(2)).append(SeparatorConstants.COL_SEPARATOR);
                            sb.append(matcher.group(4)).append(SeparatorConstants.COL_SEPARATOR);
                            sb.append(matcher.group(3)).append(SeparatorConstants.LIN_SEPARATOR);
                        }
                        if (!flag && matcher.group(3).trim().equals(timeStamp.trim())) {
                            flag = true;
                        }
                    }
                }
                this.savePersistentData(ip + "failedlogin", newTimeStamp);
                propValues[0] = ResPropertyValue.createPropValue(failedLoginUnm + "", propMetas[0]);
                propValues[1] = ResPropertyValue.createPropValue(sb.toString(), propMetas[1]);
                propertyValueX.setValues(propValues);
                values.add(propertyValueX);
            } else {
                reader = CommandReader.getReader(ip, ". ./.profile;who /etc/security/failedlogin |tail -1", 0, 0);
                if (reader != null && (strLine = reader.readLine()) != null) {
                    Matcher matcher = pattern.matcher(strLine);
                    if (matcher.find()) {
                        this.savePersistentData(ip + "failedlogin", matcher.group(3));
                    }
                }
                propValues[0] = ResPropertyValue.createPropValue(0 + "", propMetas[0]);
                propValues[1] = ResPropertyValue.createPropValue("", propMetas[1]);
                propertyValueX.setValues(propValues);
                values.add(propertyValueX);
            }
        } catch (Exception e) {
            logger.error("failed to collect FailedLoginCollector");
            throw new CollectorException(e);
        }
        return values;
    }
}
